package com.browsesoft.htmlcomponent;

import java.util.Hashtable;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.browsesoft.ManagerGroup;
import com.browsesoft.SequenceFind;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.log.LogHelper;
import com.browsesoft.user.User;

public class HTMLDBFormModel implements HTMLFormModel {
	/**
	 * 操作的数据库表名
	 */
	protected String tableName = null;

	protected HTMLBasicComponent component = null;

	/**
	 * 要编辑的hashtable值
	 */
	protected Hashtable attributes = new Hashtable();

	/**
	 * 父ID
	 */
	protected String parentID = null;

	protected User loginUser = null;

	public HTMLDBFormModel() {
		try {
			// 插入新的
			attributes = new Hashtable();
			// 设置序列号
			String ID = Integer.toString(SequenceFind.getID());
			attributes.put("id", ID);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化model
	 */
	public void init(HttpServletRequest request) throws Exception {
		this.loginUser = (User) request.getSession().getAttribute("loginUser");
		if (request.getParameter("templatename") != null
				& !request.getParameter("templatename").equals("")) {
			String name = request.getParameter("templatename");
			// 加载模板
			TemplateManager manager = (TemplateManager) ManagerGroup
					.getManagerGroup().getManager("template");
			// 根据模板名生成模板
			Template t = manager.getTemplateByName(name);
			// 得到模板文档
			// 解析文档,找出需要处理的根元素
			Element element = (Element) t.getDocument().getElementsByTagName(
					"form").item(0);
			this.tableName = element.getAttribute("name");
		}
	}

	/**
	 * 更新属性
	 * 
	 * @param ht
	 *            存储属性的哈息表
	 */
	public void updateAttributes(Hashtable ht) throws Exception {
		// parentID不为空，说明是新增
		if (parentID != null) {
			// 设置父ID
			attributes.put("processid", parentID);
			attributes.putAll(ht);
			try {
				String[][] result = DBTools
						.executeQueryWithTableHead("select * from " + tableName
								+ " where id=" + (String) attributes.get("id"));
				if (result.length == 1) {
					insertToDB();
				}
				if (result.length == 2) {
					updateToDB();
				}
			} catch (Exception e) {
				insertToDB();
			}
			parentID = null;
		}
		// 更新
		this.attributes.putAll(ht);
		updateToDB();
	}

	/**
	 * 数据插入
	 */
	private void insertToDB() throws Exception {
		DBTools.insert(tableName, attributes);
		if (this.isLog()) {
			LogHelper.logEntity("insert", this.loginUser, this.component,
					attributes);
		}
	}

	/**
	 * 数据更新
	 */
	private void updateToDB() throws Exception {
		DBTools.update(tableName, (String) attributes.get("id"), attributes);
		if (this.isLog()) {
			LogHelper.logEntity("update", this.loginUser, this.component,
					attributes);
		}
	}

	/**
	 * 得到属性
	 */
	public Hashtable getAttributes() throws Exception {
		return this.attributes;
	}

	/**
	 * 得到选择列表
	 * 
	 * @param name
	 *            名字
	 */
	public Iterator getOptions(String name) throws Exception {
		return null;
	}

	/**
	 * 设置传递的参数
	 * 
	 * @param request
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 有ID，是编辑
		if (request.getParameter("id") != null) {
			String result[][] = DBTools
					.executeQueryWithTableHead("select * from " + tableName
							+ " where id=" + request.getParameter("id"));
			if (result == null || result.length < 2) {
				throw new RuntimeException("从表" + tableName + "中找不到id="
						+ request.getParameter("id") + "的对象");
			}
			attributes = DBTools.getAttributes(result, 1);
		}
		// 有ParentID，是增加
		else if (request.getParameter("parentid") != null) {
			if (parentID == null) {
				parentID = request.getParameter("parentid");
			}
		}
	}

	/**
	 * 设置模型所对应的组件
	 * 
	 * @param component
	 *            对应的组件
	 */
	public void setComponent(HTMLBasicComponent component) {
		this.component = component;
	}

	/**
	 * 模型更新页面元素
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}

	/**
	 * 是否记录日志 如果页面配置了日志元素
	 */
	private boolean isLog() {
		NodeList list = this.component.getPage().getElement()
				.getElementsByTagName("log");
		if (list.getLength() > 0) {
			return true;
		}
		return false;
	}

}
